const express = require("express");
const cors = require("cors");
const path = require("path");
const bannerRoutes = require("./src/routes/bannerRoutes");
const userRoutes = require("./src/routes/userRoutes");
const storeRoutes = require("./src/routes/storeRoutes");

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use("/uploads", express.static(path.join(__dirname, "../uploads")));

// 路由
app.use("/api/banners", bannerRoutes);
app.use("/api/users", userRoutes);
app.use("/api/stores", storeRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ success: false, message: "服务器内部错误" });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({ success: false, message: "请求的资源不存在" });
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

module.exports = app;
